import axios, { InternalAxiosRequestConfig, AxiosResponse } from "axios";
import { useUserStoreHook } from "@/store/modules/user";

// 处理代理路由方法
const appBaseList = import.meta.env.VITE_APP_BASE;
const appGroup = appBaseList.split(";");
const apiList: any = [];
appGroup.map((item: string) => {
  if (item) {
    const apiObj = {
      api: item.split(",")[0],
      target: item.split(",")[1],
    };
    apiList.push(apiObj);
  }
});

function filterBaseUrl(url: any) {
  const name = url.startsWith("/") ? url.split("/")[1] : url.split("/")[0];
  const baseURL: any = apiList.filter((item: any) => item.api === name);
  return baseURL[0]?.target;
}

// 创建 axios 实例
const service = axios.create({
  baseURL: import.meta.env.VITE_APP_BASE_API,
  timeout: 50000,
  headers: { "Content-Type": "application/json;charset=utf-8" },

});

// 请求拦截器
service.interceptors.request.use(
  (config: InternalAxiosRequestConfig) => {
    config.baseURL = filterBaseUrl(config.url); // 取消代理配置
    const userStore = useUserStoreHook();
    if (userStore.token) {
      // 接口校验
      const { tokenType, accessToken } = JSON.parse(userStore.token);
      config.headers.Authorization = tokenType + " " + accessToken;
    }
    return config;
  },
  (error: any) => {
    return Promise.reject(error);
  }
);

// 响应拦截器
service.interceptors.response.use(
  (response: AxiosResponse) => {
    const { code, message } = response.data;
    if (code === 200 || code === 300) {
      return response.data;
    }
    // 响应数据为二进制流处理(Excel导出)
    if (response.data instanceof ArrayBuffer) {
      return response;
    }
    // 401 token失效
    if (code === 401) {
      ElMessageBox.confirm("当前页面已失效，请重新登录", "提示", {
        confirmButtonText: "确定",
        showCancelButton: false,
        showClose: false,
        closeOnClickModal: false,
        type: "warning",
      }).then(() => {
        localStorage.clear();
        sessionStorage.clear();
        window.location.href = "/";
      });
    }

    ElMessage.error(message || "系统出错");
    return Promise.reject(new Error(message || "Error"));
  },
  (error: any) => {
    if (error?.response?.status === 401) {
      ElMessageBox.confirm("当前页面已失效，请重新登录", "提示", {
        confirmButtonText: "确定",
        type: "warning",
      }).then(() => {
        localStorage.clear();
        sessionStorage.clear();
        window.location.href = "/";
      });
    } else {
      ElMessage.error(
        error?.response?.statusText || error.message || "系统出错"
      );
    }
    return Promise.reject(error.message);
  }
);

// 导出 axios 实例
export default service;
